﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoMapper;
using Guan.CMS.CommandProcessor.Dispatcher;
using Guan.CMS.Data.Repositories;
using Guan.CMS.Domain.Commands.Article;
using Guan.CMS.Domain.Commands.SiteConfig;
using Guan.CMS.Model.Entities;
using Guan.CMS.Web.Core.ActionFilters;
using Guan.CMS.Web.Core.Models;
using Guan.CMS.Web.ViewModels.Page;

namespace Guan.CMS.Web.Areas.Admin.Controllers
{
    [CmsAuthorize(Roles.Admin)]
    public class PageController : Controller
    {
        private readonly ICommandBus _commandBus;
        private readonly ISiteConfigRepository _siteConfigRepository;

        public PageController(ICommandBus commandBus,ISiteConfigRepository siteConfigRepository)
        {
            this._commandBus = commandBus;
            this._siteConfigRepository = siteConfigRepository;
        }
        //
        // GET: /Admin/Page/

        public ActionResult Index()
        {
            return RedirectToAction("Aboutus");
        }

        public ActionResult Aboutus()
        {
            var vm = GetAboutusPage();
            return View(vm);
        }

        [HttpPost]
        public ActionResult Aboutus(AboutusViewModel form)
        {
            if (ModelState.IsValid)
            {
                var command = Mapper.Map<AboutusViewModel, UpdateAboutUsPageCommand>(form);
                var result = _commandBus.Submit(command);
                if (result.Success)
                {
                    return RedirectToAction("Index");
                }
            }
            return View(form);
        }

        private AboutusViewModel GetAboutusPage()
        {
            var siteConfig = _siteConfigRepository.GetList().FirstOrDefault();
            var vm = new AboutusViewModel();
            if (siteConfig!=null)
            {
                vm.Content = siteConfig.AboutUs;
            }
            return vm;
        }
    }
}
